﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Threading.Tasks;
using EasyBlog.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace EasyBlog.Controllers
{
    public class AccountController : Controller
    {
        private readonly DbWlh _db;
        private IWebHostEnvironment _hostEnv;

        public AccountController(DbWlh dbwlh, IWebHostEnvironment hostEnv)
        {
            _db = dbwlh;
            _hostEnv = hostEnv;
        }

        public IActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public IActionResult CheckUserName(string userName)
        {
            if (_db.InfoUsers.Any(ii => ii.UserName == userName))
                return Json(new { message = 1 });
            else
                return Json(new { message = 0 });
        }

        [HttpPost]
        public IActionResult Save(string userName, string password)
        {
            try
            {
                InfoUser item = new InfoUser { UserName = userName, Password = password, DTCreate = DateTime.Now };
                _db.InfoUsers.Add(item);
                _db.SaveChanges();
                return Json(new { message = "保存成功！" });

            }
            catch (Exception ex)
            {
                return Json(new { message = $"保存失败，原因：{ex.Message},{ex.InnerException}" });
            }
        }

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [ActionName("Login")]
        public async Task<ActionResult> Logining()
        {
            var userName = Request.Form["UserName"];
            var password = Request.Form["Password"];
            var item = _db.InfoUsers.Find(userName);

            if (item != null && password == item.Password)
            {
                item.DTLogin = DateTime.Now;
                _db.SaveChanges();

                //保存验证结果;
                var claims = new List<Claim>();
                claims.Add(new Claim(ClaimTypes.Name, userName));
                var claimsIdentity = new ClaimsIdentity(claims, "Cookies");
                await HttpContext.SignInAsync("Cookies", new ClaimsPrincipal(claimsIdentity));
                return RedirectToAction("Index", "Blog");
            }
            else
                ViewBag.Msg = "登陆失败";

            return View();
        }

        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync("Cookies");
            return RedirectToAction("Index", "Home");
        }

        #region 修改密码

        [Authorize]
        public IActionResult ChangePassword()
        {
            return View();
        }

        [HttpPost]
        public IActionResult CheckPassword(string pwd)
        {
            if (_db.InfoUsers.Any(ii => ii.UserName == User.Identity.Name && ii.Password == pwd))
                return Json(new { message = 1 });
            else
                return Json(new { message = 0 });
        }

        [HttpPost]
        public async Task<ActionResult> ChangePwd()
        {
            var userName = User.Identity.Name;
            var password = Request.Form["Password"];
            var item = _db.InfoUsers.Find(userName);

            if (item != null)
            {
                item.Password = password;
                _db.SaveChanges();

                //return RedirectToAction("Index", "Blog");
                return new JsonResult(new { message = "修改成功" });
            }
            else
            {
                //ViewBag.Msg = "修改失败";
                return new JsonResult(new { message = "修改失败" });
            }
        }

        #endregion

        #region 上传头像

        [Authorize]
        public IActionResult SetHeadPic()
        {
            return View();
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns>上传文件结果信息</returns>
        [HttpPost]
        [ActionName("SetHeadPic")]
        public ActionResult UploadFile()
        {
            var file = Request.Form.Files["myFile"];
            if (file != null)
            {
                using MemoryStream ms = new MemoryStream();
                file.CopyTo(ms);
                var item = _db.InfoUsers.Find(User.Identity.Name);
                item.HeaderImg = ms.ToArray();
                _db.SaveChanges();
                ViewBag.Msg = "上传成功";
                return View();
            }
            else
            {
                return Content("没有文件需要上传！");
            }
        }

        #endregion
    }
}